package com.taptech.doufu.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.bean.ActivitiesBean;
import com.taptech.doufu.bean.DynamicStatusGsonBean;
import com.taptech.doufu.bean.UserBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.adapter.personalcenter.PersonalNewDynamicAdapter;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.UIUtil.EnsureListener;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.PullToRefreshListView;
import com.taptech.doufu.ui.view.PullToRefreshListView.OnLoadAndRefreshListener;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class PersonalNewDynamicActivity extends DiaobaoBaseActivity implements HttpResponseListener
{

    private String last = "";
    private int pageIndex = 0, oldPage;
    private PullToRefreshListView listView;
    private PersonalNewDynamicAdapter adapter;
    private View nullContent;
    private String userId = "";
    Handler mHandler;
    private WaitDialog dialog;
    private View dynamicNoPublicLay;
    private LinearLayout llPublic;
    private ImageView ivPublic;
    private TextView tvPublic;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_new_dynamic);
        dialog = new WaitDialog(PersonalNewDynamicActivity.this, R.style.updateDialog, "处理中，请稍后...");
        mHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                // TODO Auto-generated method stub
                deleteDynamicMessege(msg.arg1);
            }
        };
        userId = getIntent().getStringExtra(Constant.UID);
        listView = (PullToRefreshListView) findViewById(R.id.activity_personal_new_dynamic_list);
        dynamicNoPublicLay = findViewById(R.id.dynamicNoPublicLay);
        llPublic = (LinearLayout) findViewById(R.id.llPublic);
        ivPublic = (ImageView) findViewById(R.id.ivPublic);
        tvPublic = (TextView) findViewById(R.id.tvPublic);
        llPublic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPublicStatus();
            }
        });
        initPublicBtn(userId);
        listView.setLoadmoreable(true);
        listView.setRefreshable(false);
        nullContent = findViewById(R.id.activity_personal_new_dynamic_null_tip);
        adapter = new PersonalNewDynamicAdapter(mHandler, PersonalNewDynamicActivity.this);
        listView.setAdapter(adapter);
        listView.setRefreshable(true);
        listView.setLoadmoreable(true);
        listView.setOnLoadAndRefreshListener(new OnLoadAndRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                last = "";
                pageIndex = 0;
                PersonalInfoService.getInstance().loadDynamicMine(PersonalNewDynamicActivity.this, last, pageIndex, userId);
            }

            @Override
            public void loadMore()
            {
            }
        });
        listView.setOnScrollListener(new OnScrollListener()
        {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState)
            {
                // TODO Auto-generated method stub
                listView.setCurrentScrollState(scrollState);

                if (listView.isLoadmoreable())
                {
                    // 判断是否滚动到底部
                    boolean scrollEnd = false;
                    try
                    {
                        if (view.getPositionForView(listView.getFootView()) == view.getLastVisiblePosition())
                            scrollEnd = true;
                    } catch (Exception e)
                    {
                        scrollEnd = false;
                    }
                    if (scrollEnd && !listView.isFull())
                    {
                        listView.getFootView().setVisibility(View.VISIBLE);
                        if (oldPage != pageIndex)
                        {
                            oldPage = pageIndex;
                            listView.loadMore();
                            PersonalInfoService.getInstance().loadDynamicMine(PersonalNewDynamicActivity.this, last, pageIndex, userId);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
            {
                // TODO Auto-generated method stub

            }
        });
        PersonalInfoService.getInstance().loadDynamicMine(this, last, pageIndex, userId);
    }


    private void setPublicStatus(){
        int status = 0;
        if (isPublic){
            status = 1;
        }
        ApiClient.getInstance().setUseCache(false).getService().setDynamicStatus(status)
                .compose(RxJavaHelper.<DynamicStatusGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<DynamicStatusGsonBean>(){
                    @Override
                    public void onNext(DynamicStatusGsonBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                        if (responseBaseBean != null && responseBaseBean.getData() != null &&
                                responseBaseBean.getData().getRes() > 0) {
                            isPublic = !isPublic;
                            setPubicUI();
                        }else{
                            Toast.makeText(PersonalNewDynamicActivity.this,"设置失败，请重试",Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(PersonalNewDynamicActivity.this,"设置失败，请重试",Toast.LENGTH_LONG).show();
                    }
                });
    }

    String idString;
    private int deleType;

    protected void deleteDynamicMessege(final int position)
    {
        // TODO Auto-generated method stub
        final ActivitiesBean data = (ActivitiesBean) adapter.getDataSource().get(position);
        idString = data.getParent_id();
        // Log.i("TAG", "data.getId():"+data.getId());
        int target_type = DiaobaoUtil.String2Int(data.getTarget_type());
        // Log.i("TAG", "target_type:" + target_type);
        // Log.i("TAG", "data.getParent_id():" + data.getParent_id());
        if (AccountService.getInstance().isUserSelf(userId) && (target_type != 6) && (target_type != 7))
        {

            // if (idString == null || idString.trim().length() ==
            // 0||DiaobaoUtil.String2Int(data.getParent_id())==0)
            if (target_type == 1)
            {
                idString = data.getSubobject_id();
                deleType = 1;
            }
            /*if (target_type == 2 || target_type == 3 || target_type == 4 || target_type == 5)
            {
				idString = data.getParent_id();
				deleType = 2;
			}*/
            if (target_type == 2 || target_type == 3 || target_type == 4 || target_type == 5 || target_type == 41 || target_type == 42 || target_type == 43)
            {
                idString = data.getParent_id();
                deleType = 2;
            }
            if (target_type == 45) {
                if (!TextUtils.isEmpty(data.getChild_id())&& Integer.parseInt(data.getChild_id()) > 0) {
                    //回复
                    idString = data.getChild_id();
                    deleType = 3;
                }else{
                    //评论
                    idString = data.getParent_id();
                    deleType = 2;
                }
            }
            if (target_type == 8 || target_type == 9 || target_type == 10 || target_type == 79)
            {
                idString = data.getChild_id();
                deleType = 3;
            }
            UIUtil.showEnsureDialog(PersonalNewDynamicActivity.this, "确定删除", new EnsureListener()
            {
                @Override
                public void sure()
                {
                    dialog.show();
                    switch (deleType)
                    {
                        case 1:
                            PersonalInfoService.getInstance().delTopic(idString, new HttpResponseListener()
                            {
                                @Override
                                public void handleResponse(int handleType, HttpResponseObject response)
                                {
                                    // Log.i("TAG", "data.getId():"+data.getId());
                                    dialog.dismiss();
                                    if (response.getStatus() == 0)
                                    {
                                        UIUtil.toastMessage(PersonalNewDynamicActivity.this, "删除成功！");
                                        adapter.getDataSource().remove(position);
                                        adapter.notifyDataSetChanged();

                                    } else
                                    {
                                        if (TextUtils.isEmpty(response.getUser_msg())) {
                                            UIUtil.toastMessage(PersonalNewDynamicActivity.this, "删除失败");
                                        } else {
                                            UIUtil.toastMessage(PersonalNewDynamicActivity.this, response.getUser_msg());
                                        }
                                    }

                                }
                            });
                            break;
                        case 2:
                            PersonalInfoService.getInstance().delComment(idString, new HttpResponseListener()
                            {
                                @Override
                                public void handleResponse(int handleType, HttpResponseObject response)
                                {
                                    // Log.i("TAG", "data.getId():"+data.getId());
                                    dialog.dismiss();
                                    if (response.getStatus() == 0)
                                    {
                                        UIUtil.toastMessage(PersonalNewDynamicActivity.this, "删除成功！");
                                        adapter.getDataSource().remove(position);
                                        adapter.notifyDataSetChanged();

                                    } else
                                    {
                                        if (TextUtils.isEmpty(response.getUser_msg())) {
                                            UIUtil.toastMessage(PersonalNewDynamicActivity.this, "删除失败");
                                        } else {
                                            UIUtil.toastMessage(PersonalNewDynamicActivity.this, response.getUser_msg());
                                        }
                                    }

                                }
                            });
                            break;
                        case 3:
                            PersonalInfoService.getInstance().delReply(idString, new HttpResponseListener()
                            {
                                @Override
                                public void handleResponse(int handleType, HttpResponseObject response)
                                {
                                    // Log.i("TAG", "data.getId():"+data.getId());
                                    dialog.dismiss();
                                    if (response.getStatus() == 0)
                                    {
                                        UIUtil.toastMessage(PersonalNewDynamicActivity.this, "删除成功！");
                                        adapter.getDataSource().remove(position);
                                        adapter.notifyDataSetChanged();

                                    } else {
                                        if (TextUtils.isEmpty(response.getUser_msg())) {
                                            UIUtil.toastMessage(PersonalNewDynamicActivity.this, "删除失败");
                                        } else {
                                            UIUtil.toastMessage(PersonalNewDynamicActivity.this, response.getUser_msg());
                                        }
                                    }

                                }
                            });
                            break;
                        default:
                            break;
                    }
                }

                @Override
                public void cancel()
                {
                }
            });

        }

    }

    private boolean isMine;

    private void initPublicBtn(String userId){
        String myUid = AccountService.getInstance().getUserUid();
        if (!TextUtils.isEmpty(userId) && userId.equals(myUid)){  //自己的动态
            isMine = true;
            llPublic.setVisibility(View.VISIBLE);
        }else{
            isMine = false;
            llPublic.setVisibility(View.GONE);
        }
    }

    private boolean isPublic = true;

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {
        // TODO Auto-generated method stub
        pageIndex = response.getPageIndex();
        if (DiaobaoUtil.isRequestResult(response))
        {
            JSONObject data = (JSONObject) response.getData();
            List<ActivitiesBean> dynamicList = null;
            try
            {
                if (data.has("user") && data.get("user") instanceof JSONObject)
                {
                    UserBean userBean = new UserBean();
                    userBean.setJson2(data.getJSONObject("user"));
                    adapter.setUserHead(userBean.getIcon());
                }
                if (data.has("activities") && data.get("activities") instanceof JSONArray)
                {
                    dynamicList = DiaobaoUtil.json2list(ActivitiesBean.class, data.getJSONArray("activities"));
                    if (pageIndex == 0)
                    {
                        adapter.setDataSource(dynamicList);
                    } else
                    {
                        adapter.setSuperDatas2(dynamicList);
                    }
                }

                oldPage = pageIndex;
                pageIndex = pageIndex + 1;
                last = data.getString("last");
                if (dynamicList != null && dynamicList.size() < Constant.SEPARATE_RETURN_DATA_NUMBER)
                {
                    listView.setFull(true);
                } else
                {
                    listView.setFull(false);
                }
                if (data.has("is_public")){
                    isPublic = data.getBoolean("is_public");
                }
            } catch (JSONException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else
        {
            UIUtil.toastMessage(this, DiaobaoUtil.getErrorTips(response));
            oldPage = -1;

        }
        isNotContent();
        setPubicUI();
        if (response.getPageIndex() == 0)
        {
            listView.onRefreshComplete();
        }
        listView.loadMoreComplete();
    }

    private void isNotContent() {
        if (isMine){
            dynamicNoPublicLay.setVisibility(View.GONE);
            if (adapter != null && adapter.getCount() > 0) {
                nullContent.setVisibility(View.GONE);
            } else {
                nullContent.setVisibility(View.VISIBLE);
            }
        }else{
            if (isPublic){
                dynamicNoPublicLay.setVisibility(View.GONE);
                if (adapter != null && adapter.getCount() > 0) {
                    nullContent.setVisibility(View.GONE);
                } else {
                    nullContent.setVisibility(View.VISIBLE);
                }
            }else{
                nullContent.setVisibility(View.GONE);
                dynamicNoPublicLay.setVisibility(View.VISIBLE);
            }
        }

    }

    private void setPubicUI(){
        if (isPublic){
            ivPublic.setImageResource(R.drawable.dynamic_visible);
            tvPublic.setText("公开展示");
            tvPublic.setTextColor(Color.parseColor("#fe6e6e"));
        }else{
            tvPublic.setTextColor(Color.parseColor("#303030"));
            ivPublic.setImageResource(R.drawable.dynamic_invisible);
            tvPublic.setText("自己可见");

        }
    }
}
